/**
 * Project Name:zyhj-admin
 * File Name:CommonServiceImpl.java
 * Package Name:com.vviton.zyhj.admin.service.impl
 * Date:2016年11月16日上午10:11:07
 *
 */

package com.vviton.zyhj.admin.service.impl;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.vviton.zyhj.admin.content.CommonConstants;
import com.vviton.zyhj.admin.cors.CommonCors;
import com.vviton.zyhj.admin.service.CommonService;
import com.vviton.zyhj.admin.view.ViewFirstLeafMenu;
import com.vviton.zyhj.admin.view.ViewRootMenu;
import com.vviton.zyhj.admin.view.ViewSecondLeafMenu;
import com.vviton.zyhj.common.base.AppConfig;
import com.vviton.zyhj.common.base.BaseService;
import com.vviton.zyhj.common.common.CodeConstants;
import com.vviton.zyhj.common.common.ValidatorConstants;
import com.vviton.zyhj.common.dao.TYyxtCpglLmbMapper;
import com.vviton.zyhj.common.dao.TYyxtPtglCyfxxMapper;
import com.vviton.zyhj.common.entity.TYyxtCode;
import com.vviton.zyhj.common.entity.TYyxtCpglLmb;
import com.vviton.zyhj.common.entity.TYyxtPtglCyfxx;
import com.vviton.zyhj.common.utils.FileUtils;
import com.vviton.zyhj.common.utils.HttpClientUtil;
import com.vviton.zyhj.common.utils.ImageUtil;
import com.vviton.zyhj.common.utils.ResultJson;
import com.vviton.zyhj.common.view.ParamUpload;
import com.vviton.zyhj.common.view.ViewCpglLmb;
import com.wdcloud.ptxtgl.base.entity.Menu;
import com.wdcloud.ptxtgl.sdk.PtxtglService;

/**
 * ClassName:CommonServiceImpl <br/>
 * Function: 公共接口实现. <br/>
 * Date: 2016年11月16日 上午10:11:07 <br/>
 *
 * @author huangqq
 * @version 1.0
 * @since JDK 1.7
 */
public class CommonServiceImpl extends BaseService implements CommonService {

	/** 日志 */
	private static Logger logger = Logger.getLogger(CommonServiceImpl.class);

	/** 类目Dao */
	@Autowired
	private TYyxtCpglLmbMapper tyxtCpglLmbMapper;

	/** 承运方信息Mapper */
	@Autowired
	private TYyxtPtglCyfxxMapper tYyxtPtglCyfxxMapper;
	
    /** 平台系统管理对外提供接口 */
    @Autowired
    private PtxtglService ptxtglService;

	/** 读取配置文件信息 */
	@Autowired
	private AppConfig appConfig;

	@Autowired
	private CommonCors commonCors;

	/**
	 * getLmxxList,获取礼品类目. <br/>
	 * Author: huangqq <br/>
	 * Create Date: 2016年11月16日 <br/>
	 * ===============================================================<br/>
	 * Modifier: huangqq <br/>
	 * Modify Date: 2016年11月16日 <br/>
	 * Modify Description: <br/>
	 * ===============================================================<br/>
	 *
	 * @param lmb
	 *            类目信息
	 * @return 类目集合
	 * @since JDK 1.7
	 */
	@Override
	public List<ViewCpglLmb> getLmxxList(TYyxtCpglLmb lmb) {
		lmb.setZt(CodeConstants.LPLMZT_ZC);
		return tyxtCpglLmbMapper.getLmxxList(lmb);
	}

	/**
	 *
	 * getCodeListByCodeClass,(根据codeClass取码表数据). <br/>
	 * Author: nifang <br/>
	 * Create Date: 2016年11月16日 <br/>
	 * ===============================================================<br/>
	 * Modifier: nifang <br/>
	 * Modify Date: 2016年11月16日 <br/>
	 * Modify Description: <br/>
	 * ===============================================================<br/>
	 *
	 * @param codeClass
	 *            代码
	 * @return 码表数据
	 * @since JDK 1.7
	 */
	@Override
	public List<TYyxtCode> getCodeListByCodeClass(String codeClass) {
		return super.getCodeListByCodeClass(codeClass);
	}

	/**
	 *
	 * getCyfxxToCodeList,(获取转换成码表结构的承运方信息列表). <br/>
	 * Author: nifang <br/>
	 * Create Date: 2016年11月3日 <br/>
	 * ===============================================================<br/>
	 * Modifier: nifang <br/>
	 * Modify Date: 2016年11月3日 <br/>
	 * Modify Description: <br/>
	 * ===============================================================<br/>
	 *
	 * @param shfs
	 *            送货方式
	 * @return 转换成码表结构的承运方信息列表
	 * @since JDK 1.7
	 */
	@Override
	public List<TYyxtCode> getCyfxxToCodeList(String shfs) {

		List<TYyxtCode> codeList = new ArrayList<TYyxtCode>();
		List<TYyxtPtglCyfxx> cyfxxList = tYyxtPtglCyfxxMapper
				.getCyfxxListByShfs(shfs);
		for (TYyxtPtglCyfxx cyfxx : cyfxxList) {
			TYyxtCode code = new TYyxtCode();
			code.setId(cyfxx.getId());
			code.setCode(cyfxx.getId());
			code.setCodedesc(cyfxx.getCyfmc());
			codeList.add(code);
		}
		return codeList;
	}

	/**
	 * checkLogoUrl,校验logo图片地址有效性. <br/>
	 * Author: yaojie <br/>
	 * Create Date: 2016年8月19日 <br/>
	 * ===============================================================<br/>
	 * Modifier: yaojie <br/>
	 * Modify Date: 2016年8月19日 <br/>
	 * Modify Description: <br/>
	 * ===============================================================<br/>
	 *
	 * @param logoUrl
	 *            logo地址
	 * @return 地址是否有效
	 * @since JDK 1.7
	 */
	@Override
	public ResultJson checkLogoUrl(String logoUrl) {
		ResultJson result = new ResultJson(true);
		URL url;
		try {
			url = new URL(logoUrl);
			url.openStream();
		} catch (Exception e) {
			result.setResult(false);
		}
		return result;
	}

	/**
	 * uploadLogo,根据课堂id上传图片logo. <br/>
	 * Author: wanrj <br/>
	 * Create Date: 2016年2月2日 <br/>
	 * ===============================================================<br/>
	 * Modifier: huangqq <br/>
	 * Modify Date: 2016年2月2日 <br/>
	 * Modify Description: <br/>
	 * ===============================================================<br/>
	 *
	 * @param paramUpload
	 *            上传参数包含 (ktid 课堂id,path 图片路径,x x坐标,y y坐标, w 宽度 )
	 * @return ResultJson
	 * @since JDK 1.7
	 */
	@Override
	public ResultJson uploadLogo(ParamUpload paramUpload) {
		String path = paramUpload.getPath();
		String type = paramUpload.getType();
		String jpg = "jpg";
		int leftx = (int) paramUpload.getLeftx();
		int lefty = (int) paramUpload.getLefty();
		int rightx = (int) paramUpload.getRightx();
		int righty = (int) paramUpload.getRighty();
		int scanlw = (int) paramUpload.getScanlw();
		int scanlh = (int) paramUpload.getScanlh();
		int h = paramUpload.getSelectionh();
		int w = paramUpload.getSelectionw();
		ResultJson json = new ResultJson(false);
		if (path == null || path.equals("")) {
			json.setCode(ValidatorConstants.E1013);
			return json;
		}
		try {
			Iterator<ImageReader> iterator = ImageIO
					.getImageReadersByFormatName(type);
			ImageReader reader = iterator.next();
			java.net.URL url = new java.net.URL(path);
			java.net.URLConnection conn = url.openConnection();
			java.io.InputStream is = conn.getInputStream();
			ImageInputStream iis = ImageIO.createImageInputStream(is);
			reader.setInput(iis, true);
			ImageReadParam param = reader.getDefaultReadParam();

			BufferedImage proBi = reader.read(0, param); // 原生图片加载到内存中
			ByteArrayOutputStream os = new ByteArrayOutputStream(); // 捕获内存缓冲区的数据,转换成字节数组
			ImageIO.write(proBi, type, os);
			InputStream in = new ByteArrayInputStream(os.toByteArray());
			File file = FileUtils.saveTempFileByInputStream(in, UUID
					.randomUUID().toString() + "." + type);
			File cutfile = FileUtils.saveTempFileByInputStream(in, UUID
					.randomUUID().toString() + "." + jpg);
			ImageUtil.resizeImg(file, cutfile, scanlw, scanlh, 1f);
			logger.info("X坐标:" + leftx);
			logger.info("y坐标:" + lefty);
			logger.info("X坐标:" + rightx);
			logger.info("y坐标:" + righty);
			InputStream cutin = new FileInputStream(cutfile);
			ImageInputStream cutiis = ImageIO.createImageInputStream(cutin);
			Iterator<ImageReader> cutiterator = ImageIO
					.getImageReadersByFormatName(jpg);
			ImageReader cutreader = cutiterator.next();
			cutreader.setInput(cutiis, true);
			ImageReadParam cutparam = cutreader.getDefaultReadParam();
			Rectangle cutrect = new Rectangle(leftx, lefty, w, h);
			cutparam.setSourceRegion(cutrect);
			BufferedImage cutbi = cutreader.read(0, cutparam); // 裁剪图片加载到内存中
			ByteArrayOutputStream cutos = new ByteArrayOutputStream(); // 捕获内存缓冲区的数据,转换成字节数组
			ImageIO.write(cutbi, type, cutos);
			InputStream aftercutin = new ByteArrayInputStream(
					cutos.toByteArray());
			cutfile = FileUtils.saveTempFileByInputStream(aftercutin, UUID
					.randomUUID().toString() + "." + type);

			ResultJson ret = HttpClientUtil.httpPostFile(
					appConfig.getDfsUploadUrl(), cutfile);
			if (ret.isResult()) {
				json.setResult(true);
				json.setObject(ret.getMessage());
			}
			file.delete();
			cutfile.delete();
		} catch (IOException e) {
			json.setCode(ValidatorConstants.E1014);
			e.printStackTrace();
		}

		return json;
	}

	/**
	 * getDqdmList,获取地区代码集合. <br/>
	 * Author: huangqq <br/>
	 * Create Date: 2016年4月20日 <br/>
	 * ===============================================================<br/>
	 * Modifier: huangqq <br/>
	 * Modify Date: 2016年4月20日 <br/>
	 * Modify Description: <br/>
	 * ===============================================================<br/>
	 *
	 * @param lang
	 *            语言
	 * @return 地区代码集合
	 * @since JDK 1.7
	 */
	@Override
	public List<TYyxtCode> getDqdmList(String lang) {
		return commonCors.getDqdmList(lang);
	}

	/**
	 * getZhlxList,获取账号类型集合. <br/>
	 * Author: yaojie <br/>
	 * Create Date: 2016年4月29日 <br/>
	 * =============================================================== <br/>
	 * Modifier: yaojie <br/>
	 * Modify Date: 2016年4月29日 <br/>
	 * Modify Description: <br/>
	 * =============================================================== <br/>
	 *
	 * @param lang
	 *            语言
	 * @return 账号类型集合
	 * @since JDK 1.7
	 */
	@Override
	public List<TYyxtCode> getZhlxList(String lang) {
		return commonCors.getZhlxList(lang);
	}

	/**
	 * getXwList,获取行为集合. <br/>
	 * Author: huangqq <br/>
	 * Create Date: 2016年4月20日 <br/>
	 * ===============================================================<br/>
	 * Modifier: huangqq <br/>
	 * Modify Date: 2016年4月20日 <br/>
	 * Modify Description: <br/>
	 * ===============================================================<br/>
	 *
	 * @param lang
	 *            语言
	 * @return 行为集合
	 * @since JDK 1.7
	 */
	@Override
	public List<TYyxtCode> getXwList(String lang) {
		return commonCors.getXwList(lang);
	}
	
	/**
    *
    * getMenu,(获取登录用户菜单). <br/>
    * Author: zhijian.zhang <br/>
    * Create Date: 2017年3月22日 <br/>
    * ===============================================================<br/>
    * Modifier: zhijian.zhang <br/>
    * Modify Date: 2017年3月22日 <br/>
    * Modify Description: <br/>
    * ===============================================================<br/>
    *
    * @param userid 用户id
    * @return ViewRootMenu
    * @since JDK 1.7
    */
	@Override
    public ViewRootMenu getMenu(String userid) {

        String appkey = CommonConstants.ZYHJ_APPKEY;
        Menu menu = ptxtglService.getMenusByUser(userid, appkey);
        // 重新封装
        ViewRootMenu viewRootMenu = new ViewRootMenu();

        // 根节点
        viewRootMenu.setResult(menu.isResult());
        viewRootMenu.setMsg(menu.getMsg());
        viewRootMenu.setRoot(menu.isRoot());
        viewRootMenu.setAuth(menu.isAuth());
        viewRootMenu.setDisplay(menu.isDisplay());
        viewRootMenu.setId(menu.getId());
        viewRootMenu.setParentId(menu.getParentId());
        viewRootMenu.setModulecode(menu.getModulecode());
        viewRootMenu.setModulename(menu.getModulename());
        viewRootMenu.setMenuid(menu.getMenuid());
        viewRootMenu.setResourceurl(menu.getResourceurl());
        // 第一层叶子节点
        List<Menu> firstMenuList = menu.getChild();
        if (firstMenuList != null && firstMenuList.size() > 0) {
            List<ViewFirstLeafMenu> viewFirstLeafMenuList = new ArrayList<ViewFirstLeafMenu>();
            for (Menu firstMenuInfo : firstMenuList) {
                ViewFirstLeafMenu viewFirstLeafMenu = new ViewFirstLeafMenu();
                viewFirstLeafMenu.setResult(firstMenuInfo.isResult());
                viewFirstLeafMenu.setMsg(firstMenuInfo.getMsg());
                viewFirstLeafMenu.setRoot(firstMenuInfo.isRoot());
                viewFirstLeafMenu.setAuth(firstMenuInfo.isAuth());
                viewFirstLeafMenu.setDisplay(firstMenuInfo.isDisplay());
                viewFirstLeafMenu.setId(firstMenuInfo.getId());
                viewFirstLeafMenu.setParentId(firstMenuInfo.getParentId());
                viewFirstLeafMenu.setModulecode(firstMenuInfo.getModulecode());
                viewFirstLeafMenu.setModulename(firstMenuInfo.getModulename());
                viewFirstLeafMenu.setMenuid(firstMenuInfo.getMenuid());
                viewFirstLeafMenu.setResourceurl(firstMenuInfo.getResourceurl());

                // 第二层叶子节点
                List<Menu> secondMenuList = firstMenuInfo.getChild();
                if (secondMenuList != null && secondMenuList.size() > 0) {
                    List<ViewSecondLeafMenu> viewSecondLeafMenuList = new ArrayList<ViewSecondLeafMenu>();
                    for (Menu secondMenuInfo : secondMenuList) {
                        ViewSecondLeafMenu viewSecondLeafMenu = new ViewSecondLeafMenu();
                        viewSecondLeafMenu.setResult(secondMenuInfo.isResult());
                        viewSecondLeafMenu.setMsg(secondMenuInfo.getMsg());
                        viewSecondLeafMenu.setRoot(secondMenuInfo.isRoot());
                        viewSecondLeafMenu.setAuth(secondMenuInfo.isAuth());
                        viewSecondLeafMenu.setDisplay(secondMenuInfo.isDisplay());
                        viewSecondLeafMenu.setId(secondMenuInfo.getId());
                        viewSecondLeafMenu.setParentId(secondMenuInfo.getParentId());
                        viewSecondLeafMenu.setModulecode(secondMenuInfo.getModulecode());
                        viewSecondLeafMenu.setModulename(secondMenuInfo.getModulename());
                        viewSecondLeafMenu.setMenuid(secondMenuInfo.getMenuid());
                        viewSecondLeafMenu.setResourceurl(secondMenuInfo.getResourceurl());
                        viewSecondLeafMenuList.add(viewSecondLeafMenu);

                    }
                    viewFirstLeafMenu.setChild(viewSecondLeafMenuList);
                }
                viewFirstLeafMenuList.add(viewFirstLeafMenu);
            }
            viewRootMenu.setChild(viewFirstLeafMenuList);
        }
        return viewRootMenu;
    
	}
}
